package com.azt.back.action.admin;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.Session;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.azt.api.pojo.Admin;
import com.azt.api.service.AdminService;
import com.azt.back.util.ContextUtils;
import com.azt.model.AjaxJson;
import com.azt.utils.CookieUtils;
import com.azt.utils.IpUtil;
import com.azt.utils.RequestUtils;
import com.azt.utils.SessionUtils;

@Controller
@RequestMapping("/frame")
public class FrameAction {
	private static final Logger log = LoggerFactory.getLogger(FrameAction.class);
	
	@Autowired
	private AdminService adminService;
	
	private static List<String> icons;

	@RequestMapping("index.do")
	public String index() {
		return "admin/frame/index";
	}

	@RequestMapping("main.do")
	public String main(HttpServletRequest request, ModelMap model) {
		String funcid = request.getParameter("funcid");
		model.put("funcid", funcid);
		return "admin/frame/main";
	}

	@RequestMapping("top.do")
	public String top(ModelMap model) {
		Admin admin = ContextUtils.getAdmin();
		model.addAttribute("admin", admin);
		return "admin/frame/top";
	}

	@RequestMapping("left.do")
	public String left(HttpServletRequest request, ModelMap model) {
		String funcid = request.getParameter("funcid");
		if(funcid==null){
			funcid="1";
			//记录最后一次点击的按钮
			Cookie cc = CookieUtils.getCookieByName(request, "b.azt.f");
			if(cc!=null){
				String va =cc.getValue();
				try {
					va = URLDecoder.decode(va,"UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				model.put("lastf", va);
			}
		}
		model.put("funcid", funcid);
		
		if (icons == null) {
			// 查打图标文件
			String realPath = request.getSession().getServletContext().getRealPath("/res/back/frame/css/font-awesome.min.css");
			File f = new File(realPath);
			try {
				FileInputStream fileInputStream = new FileInputStream(f);
				BufferedReader br = new BufferedReader(new InputStreamReader(fileInputStream));
				String readLine = br.readLine();
				Pattern compile = Pattern.compile(".icon-[a-zA-Z_\\-]+:before");
				List<String> list = new ArrayList<String>();
				while (readLine != null) {
					/*
					 * if(readLine.contains("icon-large")||readLine.contains(
					 * "icon-flip-horizontal")||readLine.contains(
					 * "icon-flip-vertical")||readLine.contains(
					 * "icon-flip-horizontal")||readLine.contains(
					 * "icon-flip-vertical")) continue;
					 */
					Matcher matcher = compile.matcher(readLine);
					while (matcher.find()) {

						String group = matcher.group(0);
						list.add(group.substring(1, group.length() - 7));
					}
					readLine = br.readLine();
				}
				icons = list;
			} catch (FileNotFoundException e) {
				log.error("没找到：font-awesome.min.css");
				e.printStackTrace();
			} catch (IOException e) {
				log.error("读取错误：font-awesome.min.css");
				e.printStackTrace();
			}
		}
		model.put("icons", icons);
		return "admin/frame/left";
	}

	@RequestMapping("right.do")
	public String right() {
		return "admin/frame/right";
	}
	
	@RequestMapping("bottom.do")
	public String bottom(HttpServletRequest request,ModelMap  model) {
		Admin admin = ContextUtils.getAdmin();
		model.put("admin", admin);
		String remoteAddr = request.getLocalAddr();
		try {
			remoteAddr = IpUtil.getRealIp();
		} catch (SocketException e) {
			e.printStackTrace();
		}
		
		model.put("ip", remoteAddr);
		int remotePort = request.getLocalPort();
		model.put("address", remoteAddr+":"+remotePort);
		return "admin/frame/bottom";
	}

	/**
	 * 当前在线
	 * @author 张栋  2016年7月28日下午3:40:53
	 */
	@RequestMapping("online.do")
	public String online(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		Map<String, Session> clients = SessionUtils.clients;
		Set<String> keySet = clients.keySet();
		Iterator<String> iterator = keySet.iterator();
		List<Admin> admins = new ArrayList<>();
		while (iterator.hasNext()) {
			String next = iterator.next();
			String adminid = next.split("_")[1];
			Admin admin = adminService.getAdminById(Integer.parseInt(adminid));
			admins.add(admin);
		}
		model.put("admins", admins);
		Admin admin = ContextUtils.getAdmin();
		model.put("admin", admin);
		
		return "admin/frame/online";
	}
	
	
	
	/**
	 * 发送消息
	 * @author 张栋  2016年7月29日上午9:44:51
	 */
	@RequestMapping("sendmsg.do")
	@ResponseBody
	public AjaxJson sendmsg(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		AjaxJson j = new AjaxJson();
		//发送对象
		String adminids = RequestUtils.getString(request, "adminid");
		
		//发送内容
		String message = RequestUtils.getString(request, "message");
		
		Admin admin = ContextUtils.getAdmin();
		
		List<String> asList = null;
		//指定用户为空则发送给所有人,
		if(StringUtils.isNotBlank(adminids)){
			String[] split = adminids.split(",");
			asList = Arrays.asList(split);
		}
			

		String myadminid = admin.getId()+"";
		Set<String> keySet = SessionUtils.clients.keySet();
		Iterator<String> iterator = keySet.iterator();
		while (iterator.hasNext()) {
			String next = iterator.next();
			String toadminid = next.split("_")[1];
			if(myadminid.equals(toadminid)){
				//过滤掉自己
				continue;
			}
			
			
			if(asList!=null && asList.contains(toadminid)){
				SessionUtils.sendmessage(admin.getId(), Integer.parseInt(toadminid), admin.getName(), message,"2");//弹窗提示		
			}else{
				SessionUtils.sendmessage(admin.getId(), Integer.parseInt(toadminid), admin.getName(), message,"1");//普聊		
			}
		}
		
		return j;
	}
	
	
	
	public static void main(String[] args) {
		String str = ".icon-power-off:before,.icon-off:before{";
		Pattern compile = Pattern.compile(".icon-[a-zA-Z_\\-0-9]+:before");
		Matcher matcher = compile.matcher(str);
		while (matcher.find()) {
			System.out.println(matcher.group(0));
		}
	}
}
